package simulation;

import org.junit.Test;

/**
 * @Description
 * @Author Firenut
 * @Date 2023-09-28 01:13
 */
public class T468_validIPAddress {
    @Test
    public void test() {
//        System.out.println(validIPAddress("172.16.254.1"));
        System.out.println(validIPAddress("2001:0db8:85a3:0:0:8A2E:0370:7334"));

    }

    public String validIPAddress(String queryIP) {
        if (queryIP.indexOf('.') > 0 && check4(queryIP)) return "IPv4";
        if (queryIP.indexOf(':') > 0 && check6(queryIP)) return "IPv6";
        return "Neither";
    }

    boolean check4(String ip) {
        int n = ip.length();
        int cnt = 0; // 记录小数点的个数
        char[] cs = ip.toCharArray();
        for (int i = 0; i < n && cnt <= 3; ) {
            int j = i, x = 0;
            while (x <= 255 && j < n && cs[j] >= '0' && cs[j] <= '9') {
                x = x * 10 + cs[j++] - '0';
            }
            // j没有移动，说明没有遇到数字了，该字符串不合法
            if (j == i) return false;
            // 如果出现前导0 or 数字已经超过255，该字符串不合法
            if ((j - i > 1 && cs[i] == 0) || x > 255) return false;

            i = j + 1;
            if (j == n) break;
            // 存在非'.'的非数字字符
            if (cs[j] != '.') return false;
            cnt++;
        }
        // ***
        return cnt == 3;
    }

    boolean check6(String ip) {
        int cnt = 0;
        char[] ch = ip.toCharArray();
        for (int i = 0; i < ip.length() && cnt <= 7; ) {
            int j = i;
            while (j < ip.length() && (ch[j] >= '0' && ch[j] <= '9') || (ch[j] >= 'a' && ch[j] <= 'f') || (ch[j] >= 'A' && ch[j] <= 'F')) {
                j++;
            }
            if (j == i || j - i > 4) return false;
            i = j + 1;
            if (ch[j] != ':') return false;
            cnt++;
        }
        return cnt == 7;
    }
}
